const TradingStrategy = require('./TradingStrategy');
const Order = require('../core/Order');

/**
 * 均值回归策略
 * 当价格偏离均值过多时进行反向操作
 */
class MeanReversionStrategy extends TradingStrategy {
  /**
   * 决策方法
   * @param {MarketEnvironment} market - 市场环境
   * @param {Investor} investor - 投资者
   * @returns {Order|null} 订单或null
   */
  decide(market, investor) {
    // 随机决定是否交易
    if (Math.random() > 0.3) {
      return null;
    }

    // 随机选择一个资产
    const assets = Array.from(market.assets.values());
    if (assets.length === 0) {
      return null;
    }
    
    const asset = assets[Math.floor(Math.random() * assets.length)];
    
    // 计算历史均值
    const history = asset.getHistory();
    if (history.length < 10) {
      return null;
    }
    
    // 计算最近10个时间点的均值
    const recentData = history.slice(-10);
    let sum = 0;
    for (const point of recentData) {
      sum += point.close;
    }
    const meanPrice = sum / recentData.length;
    
    // 获取当前价格
    const currentPrice = asset.getPrice();
    
    // 计算偏离度
    const deviation = (currentPrice - meanPrice) / meanPrice;
    
    // 如果偏离超过阈值，则进行反向操作
    const threshold = 0.02; // 2%阈值
    let isBuy = false;
    if (deviation > threshold) {
      // 价格过高，卖出
      isBuy = false;
    } else if (deviation < -threshold) {
      // 价格过低，买入
      isBuy = true;
    } else {
      // 未达到阈值，不操作
      return null;
    }
    
    // 确定交易价格
    const priceVariation = (Math.random() - 0.5) * 0.01; // ±0.5%的价格波动
    const price = currentPrice * (1 + priceVariation);
    
    // 根据投资者资本确定交易数量
    const maxAffordable = isBuy ? 
      Math.floor(investor.capital / price) : 
      investor.getPosition(asset.id).quantity;
      
    if (maxAffordable <= 0) {
      return null;
    }
    
    // 根据偏离程度确定交易数量
    const quantity = Math.min(
      Math.ceil(maxAffordable * Math.min(Math.abs(deviation) * 2, 1) * 0.5),
      maxAffordable
    );
    
    if (quantity <= 0) {
      return null;
    }
    
    return new Order(
      investor.id,
      asset.id,
      isBuy ? 'buy' : 'sell',
      price,
      quantity
    );
  }
}

module.exports = MeanReversionStrategy;